﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using C1.Phone.Chart;
using Microsoft.Phone.Shell;
using C1.Phone;

namespace ControlExplorer.Controls.Chart
{
    public partial class InteractiveChart
        : UserControl, IExposeApplicationBarItems
    {
        Color[] _clrs = new Color[] { Colors.Red, Colors.Green, Colors.Blue };
        ApplicationBarIconButton btnZoomOut = new ApplicationBarIconButton();

        public InteractiveChart()
        {
            InitializeComponent();

            c1chart.View.PlotBackground = new SolidColorBrush(Color.FromArgb(0, 255, 255, 255));
            c1chart.View.AxisY.MajorGridFill = new SolidColorBrush(Color.FromArgb(50, 50, 50, 50));
            btnZoomOut.Text = "zoom out";
            btnZoomOut.IconUri = new Uri("/Resources/AppBar/zoom_1-1.png", UriKind.Relative);
            btnZoomOut.Click += OnZoomOut;

            CreateSampleData(3, 200);
            c1chart.Actions.Add(new ScaleAction()); // double-tap
            c1chart.Actions.Add(new TranslateAction()); // drag

            c1chart.View.AxisX.Scale = 0.5;
        }

        Random rnd = new Random();

        void CreateSampleData(int nser, int npts)
        {
            c1chart.BeginUpdate();
            DataSeriesCollection sc = c1chart.Data.Children;
            sc.Clear();

            for (int iser = 0; iser < nser; iser++)
            {
                double phase = 0.05 + 0.1 * rnd.NextDouble();
                double amp = 1 + 5 * rnd.NextDouble();

                DataSeries ds = new DataSeries();
                double[] vals = new double[npts];
                for (int i = 0; i < npts; i++)
                    vals[i] = amp * Math.Sin(i * phase);

                ds.ValuesSource = vals;
                ds.Label = "S " + iser.ToString();

                ds.ConnectionStroke = new SolidColorBrush(_clrs[iser % 3]);
                ds.ConnectionStrokeThickness = 2;

                sc.Add(ds);
            }
            c1chart.EndUpdate();
        }

        private void OnZoomOut(object sender, EventArgs e)
        {
            c1chart.BeginUpdate();
            c1chart.View.AxisX.Scale = 1;
            c1chart.View.AxisX.Value = 0.5;
            c1chart.View.AxisY.Scale = 1;
            c1chart.View.AxisY.Value = 0.5;

            c1chart.EndUpdate();
        }

        #region IExposeApplicationBarItems Members

        public IEnumerable<IApplicationBarMenuItem> ApplicationBarItems
        {
            get 
            {
                yield return btnZoomOut;
            }
        }

        #endregion
    }
}